import moment from 'moment'
import mqtt from 'mqtt'

class TmqClient {
  constructor() {
    this.mqttUrl = 'wss://ai.seedlight.cn:31020/mqtt'
    this.username = 'admin'
    this.password = 'public'
    this.clientId = moment().format('YYYYMMDDHHmmss')
    this.client = null
    this.topic = 'test/#'
    this.msgData = null
  }

  mqttMsg() {
    if (!this.client) {
      var options = {
        connectTimeout: 40000,
        clientId: this.clientId, //提取到配置文件
        username: this.username, //提取到配置文件
        password: this.password, //提取到配置文件
        clean: true
      }
      this.client = mqtt.connect(this.mqttUrl, options)
    }
    this.client.on('connect', e => {
      console.log(e, 'MQTT链接成功！！！')
      this.client.subscribe('test/#', { qos: 0 }, error => {
        // qos 为通道
        if (!error) {
          console.log('消息订阅成功')
        } else {
          console.log('消息订阅失败')
        }
      })
    })
    // 接收消息处理
    this.client.on('message', (topic, message) => {
      // console.log('收到来自', topic, '的消息---->>', message.toString())
      this.msgData = message.toString()
    })
    // 断开发起重连
    this.client.on('reconnect', error => {
      console.log('正在重连:', error)
    })
    // 链接异常处理
    this.client.on('error', error => {
      console.log('连接失败:', error)
    })
  }
}

export default TmqClient
